package com.itlong.cloud.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.property.PropertyDeviceAlarmInfoDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.property.CloudElevatorVO;
import com.itlong.cloud.POJO.VO.property.PropertyDeviceAlarmInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.commons.dao.ICloudElevatorDao;
import com.itlong.cloud.commons.dao.IPushCloudElevatorChangeLogDao;
import com.itlong.cloud.commons.thread.queue.process.queue.SendIotPushMessageQueue;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.IotCloudCtrlInstructEnum;
import com.itlong.cloud.property.dao.IPropertyDeviceAlarmDao;
import com.itlong.cloud.property.dao.IPropertyElevatorDao;
import com.itlong.cloud.property.service.IPropertyDeviceAlarmService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.PageByVisitor;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <desc>
 *      设备告警暴服务层接口实现类
 * </desc>
 *
 * @createDate 2021/05/31
 **/
@Service
public class PropertyDeviceAlarmServiceImpl implements IPropertyDeviceAlarmService {

    @Autowired
    IPushCloudElevatorChangeLogDao iPushCloudElevatorChangeLogDao;

    //物业电梯持久层接口
    @Autowired
    private IPropertyElevatorDao iPropertyElevatorDao;

    @Autowired
    private IPropertyDeviceAlarmDao iPropertyDeviceAlarmDao;

    @Autowired
    ICloudElevatorDao iCloudElevatorDao;

    @Autowired
    SendIotPushMessageQueue sendIotPushMessageQueue;

    /**
     * <desc>
     *      实时抓拍或撤消告警
     * <desc/>
     *
     * @param  alarmInfoDTO 告警相关数据
     * @return
     * @author Juguang.S
     * @createDate 2021-05-31
     */
    @Override
    public void realTimeSnapshotOrCancelAlarm(PropertyDeviceAlarmInfoDTO alarmInfoDTO) throws Exception {
        String alarmId = alarmInfoDTO.getAlarmId();
        String type = alarmInfoDTO.getType();
        //查询出该告警消息所属摄像头所关联的电梯deviceUnique
        String deviceUnique = iPropertyElevatorDao.getElevatorDeviceUniqueByAralmId(alarmId);
        String commandType = "";
        if("1".equals(type)){
            //实时抓拍时，由于底层组装需要，暂先借助commandType字段进行区分 实时抓拍 commandType为snapshot+alarmId alarmId设备上传抓拍事件时需将此传入 撤消告警commandType为cancelAlarm
            commandType = String.format("%s%s","snapshot",alarmId);
            DeviceAlarmMessageInfoPO alarmMessageInfoPOByUpdate = new DeviceAlarmMessageInfoPO();
            List<Map<String, Object>> alarmListByUpdate = new ArrayList<>();
            alarmMessageInfoPOByUpdate.setAlarmId(alarmId);
            alarmMessageInfoPOByUpdate.setClickMark(0);
            alarmMessageInfoPOByUpdate.setUpdateTime(new Date());
            alarmListByUpdate.add(SqlUtil.durableData(alarmMessageInfoPOByUpdate, PlatformConstants.TABLE_UPDATE));
            if(alarmListByUpdate!=null && alarmListByUpdate.size()>0){
                iCloudElevatorDao.batchUpdate(alarmListByUpdate);
            }
        }else{
            commandType = "cancelAlarm";
        }
        //取得版本和iotkey
        ProductTypePO productKey = iPushCloudElevatorChangeLogDao.getElevatorVersonIotkey(deviceUnique);
        SendPushMessageTaskPO sendPushMessageTaskPO = new SendPushMessageTaskPO(productKey.getIotProductKey(),
                "/" +  deviceUnique  + (productKey.getIotVersion() == 1 ? "/user" : "") + IotCloudCtrlInstructEnum.DEVICECMD.getUrl(),
                deviceUnique,"itlong","webcam",0,commandType,1,2);
        sendIotPushMessageQueue.getSendIotPushQueue().put(sendPushMessageTaskPO);

        //保存操作日志
        this.saveSpecialLog(alarmInfoDTO);
    }

    /**
     * <desc>
     *      根据告警id查询电梯相关信息
     * <desc/>
     *
     * @param  alarmId 告警ID
     * @return
     * @author Juguang.S
     * @createDate 2021-05-31
     */
    public CloudElevatorVO getElevatorInfoByAlarmId(String alarmId) throws Exception{
        return iPropertyDeviceAlarmDao.getElevatorInfoByAlarmId(alarmId);
    }

    /**
     * <desc>
     *      根据告警id查询电梯相关信息
     * <desc/>
     *
     * @param  alarmInfoDTO 告警数据
     * @return
     * @author Juguang.S
     * @createDate 2021-05-31
     */
    private void saveSpecialLog(PropertyDeviceAlarmInfoDTO alarmInfoDTO){
        // 保存特殊操作日志
        PropertyUserInfoPO propertyUserInfoPO = iPropertyElevatorDao.getUserInfoByUserId(alarmInfoDTO.getLoginUserId());
        Date nowTime =  new Date();
        List<OperationSpecialLogPO> list = new ArrayList<>();
        OperationSpecialLogPO operationSpecialLogPO = new OperationSpecialLogPO();
        operationSpecialLogPO.setLogId(LogicIdUtil.bussinessId());
        operationSpecialLogPO.setOuterId(alarmInfoDTO.getAlarmId());
        operationSpecialLogPO.setAccount(propertyUserInfoPO.getUserName());
        operationSpecialLogPO.setRealName(propertyUserInfoPO.getRealName());
        operationSpecialLogPO.setIp(alarmInfoDTO.getIp());
        //7为设备告警
        operationSpecialLogPO.setFunctionType(7);
        if(StringUtils.isNotBlank(alarmInfoDTO.getType()) && alarmInfoDTO.getType().equals("1")){
            operationSpecialLogPO.setOperateDec(propertyUserInfoPO.getRealName() + "执行实时抓拍");
            operationSpecialLogPO.setOperateWay("实时抓拍");
        }else if(StringUtils.isNotBlank(alarmInfoDTO.getType()) && alarmInfoDTO.getType().equals("2")){
            operationSpecialLogPO.setOperateDec(propertyUserInfoPO.getRealName() + "执行撤消告警");
            operationSpecialLogPO.setOperateWay("撤消告警");
        }
        operationSpecialLogPO.setOperateFunction("/系统消息/设备告警");
        operationSpecialLogPO.setOperateData(JSON.toJSONString(alarmInfoDTO));
        operationSpecialLogPO.setStatus(DataStatusEnum.NORMAL.getType());
        operationSpecialLogPO.setCreateTime(nowTime);
        operationSpecialLogPO.setUpdateTime(nowTime);
        list.add(operationSpecialLogPO);
        iPropertyElevatorDao.batchSaveOperationLogData(list);
    }

    /**
     * <desc>
     *      获取告警消息列表
     * </desc>
     *
     * @param alarmInfoDTO 获取获取告警消息列表DTO
     * @return 分页告警消息列表
     * @author Juguang.S
     * @createDate 2021/06/07
     */
    public PageByVisitor<PropertyDeviceAlarmInfoVO> getPage(PropertyDeviceAlarmInfoDTO alarmInfoDTO) throws Exception{

        if (StringUtils.isBlank(alarmInfoDTO.getOrderColumn())) {
            alarmInfoDTO.setOrderColumn("alarm_time");
            alarmInfoDTO.setOrderRule("DESC");
        }
        //将DTO转换为Map params
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(alarmInfoDTO);
        Map<String, Object> unCheckParams = new HashMap<>();
        //分页类默认pageSize为20
        PageByVisitor<PropertyDeviceAlarmInfoVO> page = new PageByVisitor<>();
        page.getPage().setPageSize(alarmInfoDTO.getPageSize());
        page.getPage().setCurrentPage(alarmInfoDTO.getCurrentPage());
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());

        List<PropertyDeviceAlarmInfoVO> list = iPropertyDeviceAlarmDao.getDeviceAlarmByPage(params);
        page.setRows(list,iPropertyDeviceAlarmDao.getDeviceAlarmByPageCount(params));
        unCheckParams.put("mark", "0");
        unCheckParams.put("projectId", alarmInfoDTO.getProjectId());
        page.setVisitorCount(iPropertyDeviceAlarmDao.getDeviceAlarmByPageCount(unCheckParams));
        return page;
    }

    /**
     * <desc>
     *      修改设备告警消息的状态。
     * <desc/>
     *
     * @param  messageId 消息ID 多个以逗号隔开
     * @param  type 修改类型 0删除 1修改状态为已读
     * @return
     * @author Juguang.S
     * @createDate 2021/06/07
     */
    @Override
    public void updateMessageInfo(String messageId, String type) {
        String[] messageArr = messageId.split(",");
        Map<String,Object> params = new HashMap<>();
        params.put("messageArr",messageArr);
        params.put("type",type);

        iPropertyDeviceAlarmDao.updateMessageInfo(params);
    }

}
